<script lang="ts" setup>
import { type FormInstance, Message } from '@arco-design/web-vue'
import { CouponApi } from '@/apis'
import { useForm } from '@/hooks'
import { Regexp } from '@/utils'
import RangePicker from '@/components/common/RangePicker.vue'

const emit = defineEmits(['change'])

const visible = ref(false)
const loading = ref(false)
const readonly = ref(true)

const dataId = ref('')
const dataDetail = ref<CouponApi.CouponTemplateResp>()

const isCreateMode = computed(() => dataId.value === '')
const title = computed(() => (isCreateMode.value ? '创建优惠券模板' : '编辑优惠券模板'))

const nowDate = new Date()

const formRef = ref<FormInstance>()
const { form, resetForm } = useForm({
  name: null,
  image: null,
  discountType: 'MJ',
  discountAmount: null,
  maxDiscountAmount: 0,
  thresholdAmount: 0,
  distributedCount: 0,
  singleClassIdLimit: null,
  classCategoryLimit: null,
  classSubjectLimit: null,
  classGradeLimit: null,
  classTermLimit: null,
  classYearLimit: null,
  stackingUseEnabled: true,
  multipleUseEnabled: false,
  receiveLimitCount: 1,
  validType: 'FIXED',
  startValidTime: null,
  endValidTime: null,
  validDays: null,
  status: 1,
  description: null,
})

const validValidator = (value, callback) => {
  if (value === 'FIXED') {
    if (!form.startValidTime || !form.startValidTime) {
      callback('请输入有效的优惠券使用时间')
    }
  } else if (value === 'DAYS') {
    if (!form.validDays || form.validDays <= 0) {
      callback('请输入有效的优惠券使用时间')
    }
  }
}

const yearOptions = ref([])
const currentYear = new Date().getFullYear()
for (let i = -3; i <= 3; i++) {
  yearOptions.value.push({
    value: currentYear + i,
    label: `${currentYear + i}`,
  })
}

const rules: FormInstance['rules'] = {
  name: [{ required: true, match: Regexp.Name, message: '名称只能含有中文、数字、英文、下划线、短横线，长度为2-32位' }],
  discountType: [{ required: true, message: '请选择优惠券类型' }],
  discountAmount: [{ required: true, min: 0, message: '请输入优惠数量' }],
  maxDiscountAmount: [{ required: true, min: 0, message: '请输入优惠上限' }],
  distributedCount: [{ required: true, min: 0, message: '请输入发放数量' }],
  receiveLimitCount: [{ required: true, min: 0, message: '请输入每人限领数量' }],
  validType: [{ required: true, message: '请指定有效期' }, { validator: validValidator }],
}

// 优惠提示
const zkAmountTip = computed(() => {
  if (form.discountAmount) {
    return `打${form.discountAmount / 10}折`
  } else {
    return ''
  }
})
const maxDiscountAmountTip = computed(() => {
  if (form.maxDiscountAmount) {
    return `最大优惠${form.maxDiscountAmount}元`
  } else {
    return '无限制'
  }
})

const thresholdAmountTip = computed(() => {
  if (form.thresholdAmount) {
    return `满${form.thresholdAmount}元可用`
  } else {
    return '无门槛'
  }
})

// 查询详情
const getDataDetail = async () => {
  dataDetail.value = await CouponApi.getCouponTemplateDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  loading.value = false
}

// 打开详情
const open = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = true
  getDataDetail()
}

// 打开编辑
const edit = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = false
  getDataDetail()
}

// 打开新增
const create = async () => {
  dataId.value = ''
  loading.value = false
  visible.value = true
  readonly.value = false
}

// 保存
const onSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  if (isCreateMode.value) {
    await CouponApi.createCouponTemplate(form)
    Message.success('添加成功')
  } else {
    await CouponApi.updateCouponTemplate(form, dataId.value)
    Message.success('修改成功')
  }
  emit('change')
  visible.value = false
  return true
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

defineExpose({ open, edit, create })
</script>

<template>
  <ProFormPanel
    v-model:visible="visible"
    mode="drawer"
    :title="title"
    :loading="loading"
    :footer="true"
    @confirm="onSave"
    @close="reset"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules :readonly>
      <a-card title="基础信息" class="section">
        <a-row :gutter="28">
          <readonly-form-item label="优惠券名称" field="name">
            <a-input v-model.trim="form.name" placeholder="请输入优惠券名称" />
          </readonly-form-item>
          <readonly-form-item label="优惠券类型" field="discountType">
            <DictSelect v-model="form.discountType" type="button" code="DiscountTypeEnum" />
          </readonly-form-item>
          <readonly-form-item v-if="form.discountType === 'MJ'" label="优惠金额" :span="12" field="discountAmount">
            <a-input-number v-model.trim="form.discountAmount" :min="0" placeholder="请输入优惠券面额">
              <template #prepend>
                减
              </template>
              <template #append>
                元
              </template>
            </a-input-number>
          </readonly-form-item>
          <readonly-form-item v-if="form.discountType === 'ZK'" label="折扣数量" :span="12" field="discountAmount" :help="zkAmountTip">
            <a-input-number v-model.trim="form.discountAmount" :min="0" :max="100" placeholder="请输入折扣数量">
              <template #prepend>
                折扣
              </template>
              <template #append>
                %
              </template>
            </a-input-number>
          </readonly-form-item>
          <readonly-form-item label="优惠上限" :span="12" field="maxDiscountAmount" tooltip="最大优惠金额，填0代表无上限" :help="maxDiscountAmountTip">
            <a-input-number v-model.trim="form.maxDiscountAmount" :min="0" placeholder="请输入优惠上限">
              <template #prepend>
                最多优惠
              </template>
              <template #append>
                元
              </template>
            </a-input-number>
          </readonly-form-item>

          <readonly-form-item label="发放数量" field="distributedCount" tooltip="优惠券总数，超过则无法继续发放">
            <a-input-number v-model.trim="form.distributedCount" hide-button placeholder="请输入发放数量">
              <template #append>
                张
              </template>
            </a-input-number>
          </readonly-form-item>

          <readonly-form-item label="每人限领" field="receiveLimitCount" tooltip="每位家长限领数量，填0则代表无限制">
            <a-input-number v-model.trim="form.receiveLimitCount" hide-button placeholder="请输入限领数量">
              <template #append>
                张
              </template>
            </a-input-number>
          </readonly-form-item>
        </a-row>
      </a-card>
      <readonly-form-item label="有效期" field="validType" :span="24" tooltip="有效期设定为固定时间，编辑保存后对所有优惠券生效，设置为领券当日起多少天内可用，编辑保存后仅对后续领取的券生效">
        <a-radio-group v-model="form.validType">
          <a-form-item :hide-label="true" field="validRange">
            <a-radio value="FIXED" />
            <span class="mr">固定时间</span>
            <RangePicker v-model:from="form.startValidTime" v-model:to="form.endValidTime" show-time format="YYYY-MM-DD HH:mm" />
          </a-form-item>
          <a-form-item :hide-label="true" field="validCount">
            <a-radio value="DAYS" />
            <span class="mr">从领券起</span>
            <a-input-number v-model.trim="form.validDays" placeholder="多少" hide-button style="flex:1" />
            <span class="ml">天内可用</span>
          </a-form-item>
        </a-radio-group>
      </readonly-form-item>
      <a-card title="使用条件" class="section">
        <a-alert class="mb" closable>
          多个限制条件之间为“且”关系，即需同时满足多个条件才能使用
        </a-alert>
        <a-row :gutter="28">
          <readonly-form-item label="允许叠加使用" field="stackingUseEnabled" :span="12" tooltip="开启叠加使用，可以与其他可叠加优惠券一起使用，先满减再折扣；未开启时，用了该优惠券就不能再使用其他优惠券。">
            <a-switch v-model="form.stackingUseEnabled" type="round" />
          </readonly-form-item>
          <readonly-form-item label="允许多张同时使用" field="multipleUseEnabled" :span="12" tooltip="开启多张同时使用，允许同一订单使用多张相同优惠券">
            <a-switch v-model="form.multipleUseEnabled" type="round" />
          </readonly-form-item>
          <readonly-form-item label="使用门槛" field="thresholdAmount" :span="12" tooltip="填0代表无门槛" :help="thresholdAmountTip">
            <a-input-number v-model.trim="form.thresholdAmount" :min="0" placeholder="多少">
              <template #prepend>
                满
              </template>
              <template #append>
                元可用
              </template>
            </a-input-number>
          </readonly-form-item>

          <readonly-form-item label="限制班级" field="singleClassIdLimit" :span="24">
            <ClassSelect v-model="form.singleClassIdLimit" />
          </readonly-form-item>
          <readonly-form-item label="限制班型" field="classCategoryLimit" :span="24">
            <DictSelect v-model="form.classCategoryLimit" code="ClassCategoryEnum" :multiple="true" />
          </readonly-form-item>
          <readonly-form-item label="限制科目" field="classSubjectLimit" :span="24">
            <DictSelect v-model="form.classSubjectLimit" code="Subject" :multiple="true" />
          </readonly-form-item>
          <readonly-form-item label="限制年级" field="classGradeLimit" :span="24">
            <DictSelect v-model="form.classGradeLimit" code="Grade" :multiple="true" />
          </readonly-form-item>
          <readonly-form-item label="限制学期" field="classTermLimit" :span="24">
            <DictSelect v-model="form.classTermLimit" code="TermEnum" :multiple="true" />
          </readonly-form-item>
          <a-col :span="24">
            <a-form-item label="限制学年" field="classYearLimit" :span="24">
              <a-select v-model="form.classYearLimit" :options="yearOptions" multiple />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <a-card title="其他" class="section">
        <a-row :gutter="28">
          <readonly-form-item label="状态" field="status">
            <DictSelect v-model="form.status" type="status" code="CommonStatusEnum" />
          </readonly-form-item>
          <readonly-form-item label="描述" field="description" :span="24">
            <a-textarea v-model.trim="form.description" placeholder="请输入描述" :max-length="255" show-word-limit />
          </readonly-form-item>
        </a-row>
      </a-card>
    </a-form>
  </ProFormPanel>
</template>

<style lang="less" scoped>

</style>
